<?php

namespace App\Http\Controllers\Adm\Order;

use App\Libs\Cos;
use App\Libs\qCould\CosClient;
use App\Models\goods;
use App\Models\goods_attr_val;
use App\Models\goods_image;
use App\Models\order_goods;
use App\Models\order_info;
use App\Models\reservation;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class OrderController extends Controller
{
    /**
     * 首页--基础数据
     */
    public function index(Request $request)
    {
        $info = [];
        //设备总数
        $info['client_num'] = client::where(['ds'=>NULL])->count();
        $info['client_online_num'] = client::where(['ds'=>NULL,'isOnline'=>1])->count();

        $start_time = strtotime(date('Y-m-d'));
        $today_money_onumber = order_info::getPayedOrderNums(0,0,$start_time,0,0);//今日收益今日订单
        $today_withdra = settle_order::getSumMoney($start_time);//今日提现
        $today_customer = customer::getCount($start_time);//今日新增用户

        $info['today_money'] = $today_money_onumber['money'];
        $info['today_orders'] = $today_money_onumber['count'];
        $info['today_withdraw'] = $today_withdra;
        $info['today_customer'] = $today_customer;

        $end_time = $start_time;
        $start_time = $end_time - 60*60*24;
        $yester_omoney_onumber = order_info::getPayedOrderNums(0,0,$start_time,$end_time,0);//昨日收益昨日订单
        $yester_withdra = settle_order::getSumMoney($start_time,$end_time);//昨日提现
        $yester_customer = customer::getCount($start_time,$end_time);//昨日新增用户

        $info['vs_today_money'] = round($today_money_onumber['money']-$yester_omoney_onumber['money'],2);
        $info['vs_today_orders'] = $today_money_onumber['count']-$yester_omoney_onumber['count'];
        $info['vs_today_withdraw'] = $today_withdra-$yester_withdra;
        $info['vs_today_customer'] = $today_customer - $yester_customer;


        // 资金报表
        $month_order_arr = '[';
        for ($i=1; $i<=12; $i++) {
            $endStr = ($i == 12) ? ']' : ',';
            // 提现月数据
            $n1time = strtotime(date('Y').'-'.$i.'-1');
            $n2time = 0;
            if($i < 12)
            {
                $n2time = strtotime(date('Y').'-'.($i+1).'-1');
            }
            $month_order = order_info::getPayedOrderNums(0,0,$n1time,$n2time,0);
            $month_order_arr .= $month_order['money'].$endStr; // 月提现数据容器
        }
        $info['year_data_arr'] = '[]';
        $info['year_order_arr'] = $month_order_arr;

        // 组数据 周
        $time = strtotime(date('Y-m-d',time()-6*24*60*60));
        $time_arr = '["'.date('m月d日',$time).'"'; // 时间段容器
        $success_order= order_info::total_order_num(['order_status'=>2,'is_checked'=>1], $time, $time+24*60*60);
        $time_data_arr1 = '['.$success_order['order_total']; // 周数据容器--成功订单数
        $refund_order= order_info::total_order_num(['order_status'=>4], $time, $time+24*60*60);
        $time_data_arr2 = '['.$refund_order['order_total']; // 周数据容器--退款订单数
        $order_money= order_info::total_order_num(['order_status'=>2], $time, $time+24*60*60,1);
        $time_data_arr3 = '['.$order_money['order_pay_money']; // 周数据容器--订单金额

        for ($i=1; $i<7; $i++) {
            $time += 24 * 60 * 60;
            $time_arr .= ',"' . date('m月d日', $time) . '"';
            // 提现额数据
            $success_order= order_info::total_order_num(['order_status'=>2,'is_checked'=>1], $time, $time+24*60*60);
            $time_data_arr1 .= ',' . $success_order['order_total'];
            $refund_order= order_info::total_order_num(['order_status'=>4], $time, $time+24*60*60);
            $time_data_arr2 .= ',' . $refund_order['order_total'];
            $order_money= order_info::total_order_num(['order_status'=>2], $time, $time+24*60*60,1);
            $time_data_arr3 .= ',' . $order_money['order_pay_money'];
        }
        $info['time_arr'] = trim($time_arr, '"').'"]';
        $info['total_order_data1'] = $time_data_arr1.']';
        $info['total_order_data2'] = $time_data_arr2.']';
        $info['total_order_data3'] = $time_data_arr3.']';

        // 渠道商总收益排行
        $rank_list = dev_channel::orderBy('balance', 'desc')
            ->take(15)
            ->skip(0)->get()->toArray();
        foreach ($rank_list as &$v) {
            $v['channel_avatar'] = Util::getImg($v['channel_avatar']);
        }
        return view('merchantadm.order.index', ['info'=>$info, 'list'=>$rank_list]);
    }

    private  function getOrderInfo()
    {
        $start_time = strtotime(date('Y-m-d'));
        $today_money_onumber = order_info::getPayedOrderNums(0,0,$start_time,0,0);//今日收益今日订单
        $today_withdra = settle_order::getSumMoney($start_time);//今日提现
        $today_customer = customer::getCount($start_time);//今日新增用户
        $end_time = $start_time;
        $start_time = $end_time - 24 * 60 * 60;
        $yester_omoney_onumber = order_info::getPayedOrderNums(0,0,$start_time,$end_time,0);//昨日收益昨日订单
        $yester_withdra = settle_order::getSumMoney($start_time,$end_time);//昨日收益昨日订单
        $yester_customer = customer::getCount($start_time,$end_time);//昨日新增用户
        $data = [];
        $data['today'] = $today_money_onumber;
        $data['yester'] = $yester_omoney_onumber;
        $data['today_withdra'] = $today_withdra;
        $data['today_customer'] = $today_customer;
        $data['yester_withdra'] = $yester_withdra;
        $data['yester_customer'] = $yester_customer;
        $data['abnonumber'] = order_info::where('order_status',4)->count();
        return $data;
    }


    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 商品列表
     */
    public function goodsList(){
        $goods_info = goods::where(['shelves'=>1])->paginate(10);
        return view('admin.order.goodslist',['order'=>$goods_info]);
    }

    /**
     * 添加商品界面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function addGoods(Request $request)
    {
        $goods_info = [];
        $id = $request->id;
        if($id){
            $goods_info = goods::where(['id'=>$id])->first();
        }
        return view('admin/order/addgoods',['goods_info'=>isset($goods_info)?$goods_info:[]]);
    }


    /**
     * 添加商品界面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function doAddGoods(Request $request)
    {

        $title = trim($request->title);
        $price = $request->price;
        $description = $request->description;
        $img_url = $request->file('images');
        if (empty($title) || empty($img_url) || empty($price)) {
            return fun_error_view(0, '缺少参数', 'addgoods');
        }

        // 判断文件大小 文件格式
        $ext = strtolower($img_url->getClientOriginalExtension());     // 扩展名
        if (!in_array($ext, ['png', 'jpg', 'jpeg']) ) {
            return fun_error_view(0, '上传图片格式错误', 'addgoods');
        }
        if (isset($_FILES['images']['size']) && $_FILES['images']['size'] >= 8*1024*1024) {
            return fun_error_view(0, '上传图片大小不得超过8M', 'addgoods');
        }
        if (isset($_FILES['images_two']['size']) && $_FILES['images_two']['size'] >= 8*1024*1024) {
            return fun_error_view(0, '上传图片大小不得超过8M', 'addbanner');
        }

        // 轮播图
        $path = 'goods/';
        $tem_img = 'goods'.str_random(16) . '.png';
        //以读写方式打开文件，并将资源绑定到一个流上
        $content = file_get_contents($_FILES['images']['tmp_name'],'rb');
        $result = Cos::upload($content, $path.$tem_img);
        if (isset($result['code']) && $result['code'] != 0) {
            return fun_error_view(0, '上传图片失败', 'addgoods');
        }


        $tem_imgs = 'goods'.str_random(16) . '.png';
        $contents = file_get_contents($_FILES['images_two']['tmp_name'],'rb');
        $result_two = Cos::upload($contents, $path.$tem_imgs);
        if (isset($result_two['code']) && $result_two['code'] != 0) {
            return fun_error_view(0, '上传图片失败!', 'addgoods');
        }

            /*// 大图
            $path_two = '/users/banner/' . date('Y/m/d/');
            $tem_img_two  = 'banner_big_'.str_random(16) . '.png';
            $result_two = CosClient::upload($_FILES['images_two']['tmp_name'], $path_two.$tem_img_two);
            if (isset($result_two['code']) && $result_two['code'] != 0) {
                return fun_error_view(0, '上传图片失败', 'addbanner');
            }*/
        //添加商品
        $data = [
            'title' => $title,
            'discount_price' => $price,
            'goods_cover' => $result,
            'description' => $description,
        ];
        $res = goods::insertGetId($data);
        $image_res = goods_image::insertGetId(['goods_id'=>$res,'image_url'=>$result,'is_valid'=>1,'created_at'=>date('Y-m-d H:i:s')]);
        $image_res = goods_image::insertGetId(['goods_id'=>0,'image_url'=>$result_two,'is_valid'=>1,'created_at'=>date('Y-m-d H:i:s')]);
        goods::where(['id'=>$res])->update(['goods_detail_image'=>$image_res]);
        if (!$res) {
            return fun_error_view(0, '添加商品失败', 'addgoods');
        }
        return fun_error_view(0, '添加成功', 'goodslist');

    }


    public function goodsDetail(Request $request){
        $goods_id = (int) $request->goods_id;
        $goods_info = goods::where(['id'=>$goods_id])->first();
        $goods_image = goods_image::where(['id'=>$goods_info['goods_detail_image']])->first();
        $goods_info['goods_detail_image'] = $goods_image['image_url'];
        return view('admin.order.editgoods',['goods_info'=>$goods_info]);
    }


    /**
     * 删除商品
     * @param Request $request
     */
    public function delgood(Request $request)
    {
        $id = (int) $request->id;
        if (empty($id)) {
            ajax_respon(0, '缺少参数');
        }
        $info = goods::where(['id'=>$id])->update(['shelves'=>0]);
        if (empty($info)) {
            ajax_respon(0, '删除失败');
        }
        ajax_respon(1, '删除商品成功');
    }


    /**
     * 订单统计
     */
    public function orderlist(Request $request)
    {
        //$data = $this->getOrderInfo();
        $channel_account = $request->input('channel_account','');
        $order_number = $request->input('order_number','');
        $order_status = $request->input('order_status',0);
        $paytype = $request->input('paytype',0);
        $clientId = $request->input('clientid',0);
        $channel_id = $request->input('channel_id',0);
        $where = [];
        if(!empty(trim($channel_account)))
        {
            $where['cha.channel_account'] = $channel_account;
        }
        if(!empty(trim($order_number)))
        {
            $where['order_info.order_number'] = $order_number;
        }
        if($order_status>0)
        {
            $where['order_info.order_status'] = $order_status;
        }
        if($paytype>0)
        {
            $where['order_info.pay_id'] = $paytype;
        }
        if($clientId>0)
        {
            $where['order_info.clientid'] = $clientId;
        }
        if($channel_id>0)
        {
            $where['order_info.dev_channel_id'] = $channel_id;
        }
        $times = [];
        $times['k'] = !empty(trim($request->input('ktime')))?strtotime($request->input('ktime')):0;
        $times['e'] = !empty(trim($request->input('gtime')))?strtotime($request->input('gtime')):time();


        $datas = order_info::leftjoin('goods', "order_info.goods_id", "=", "goods.id")->leftjoin('address', "address.id", "=", "order_info.address_id")->whereIn('order_info.order_status',[1,2])->where($where)->orderBy('order_info.id','DESC')->select('order_info.id','order_number','goods_id','price_sum','user_id','create_time','order_status','title','original_price','retail_price','discount_price','goods_num','address.username','address.phone','address.address','integral')->paginate(15);
        if($datas){
            foreach ($datas as &$v){
            }
        }
        $data['order'] = $datas;
        $data['clientid'] = $clientId;
        $data['channel_id'] = $channel_id;
        $data['channel_account'] = $channel_account;
        $data['order_number'] = $order_number;
        $data['order_status'] = $order_status;
        $data['paytype'] = $paytype;
        $data['times'] = $times;
        return view('admin.order.ordercount',$data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 订单详情
     */
    public function orderDetail(Request $request){
        $order_id = $request->input('order_id','');
        $order_info = order_info::leftjoin('address','order_info.address_id','=','address.id')->where(['order_info.id'=>$order_id])->first();
        //查询商品
        $order_goods = order_goods::leftjoin('goods','order_goods.goods_id','=','goods.id')->where(['order_goods.order_id'=>$order_id])->get();

        return view('admin.order.orderdetail',['order_info'=>$order_info,'order_goods'=>$order_goods]);
    }


    /**
     * 订单统计
     */
    public function reservationList(Request $request)
    {
        //$data = $this->getOrderInfo();
        $channel_account = $request->input('channel_account','');
        $order_number = $request->input('order_number','');
        $order_status = $request->input('order_status',0);
        $paytype = $request->input('paytype',0);
        $clientId = $request->input('clientid',0);
        $channel_id = $request->input('channel_id',0);
        $where = [];
        if(!empty(trim($channel_account)))
        {
            $where['cha.channel_account'] = $channel_account;
        }
        if(!empty(trim($order_number)))
        {
            $where['order_info.order_number'] = $order_number;
        }
        if($order_status>0)
        {
            $where['order_info.order_status'] = $order_status;
        }
        if($paytype>0)
        {
            $where['order_info.pay_id'] = $paytype;
        }
        if($clientId>0)
        {
            $where['order_info.clientid'] = $clientId;
        }
        if($channel_id>0)
        {
            $where['order_info.dev_channel_id'] = $channel_id;
        }
        $times = [];
        $times['k'] = !empty(trim($request->input('ktime')))?strtotime($request->input('ktime')):0;
        $times['e'] = !empty(trim($request->input('gtime')))?strtotime($request->input('gtime')):time();

        $datas = reservation::leftjoin('address','reservation.address_id','=','address.id')->where($where)->orderBy('created_at','DESC')->select(['reservation.id','type','status','time','username','phone','address','created_at','estimated_weight','order_no'])->paginate(15);;
        if($datas){
            foreach ($datas as &$v){
            }
        }
        $data['order'] = $datas;
        $data['clientid'] = $clientId;
        $data['channel_id'] = $channel_id;
        $data['channel_account'] = $channel_account;
        $data['order_number'] = $order_number;
        $data['order_status'] = $order_status;
        $data['paytype'] = $paytype;
        $data['times'] = $times;
        return view('admin.order.orderreservation',$data);
    }



    /**
     * 退款订单
     */
    public function abnoorder(Request $request)
    {
        $data = $this->getOrderInfo();
        $type = $request->input('type','0');
        $where = [];
        $where['order_info.order_status'] = 4;
        $clientId = $request->input('clientid',0);
        $channel_id = $request->input('channel_id',0);
        if($clientId) $where['order_info.clientid'] = $clientId;
        if($channel_id) $where['order_info.dev_channel_id'] = $channel_id;
        $orderList = order_info::getabnormallist($where,0,time());
        foreach($orderList as $k=>$v)
        {
            // 判断退款原因
            $v['return_con'] = '未知';
            if ($v['order_status'] == 4 && !empty($v['message_id'])) {
                $msgs = geteway_message_num($v['message_id']);
                if ($msgs <= 0) {
                    $v['return_con'] = '测试数据';
                }elseif($msgs <= 1)
                {
                    $v['return_con'] = '设备未启动';
                } else {
                    $new_mgs = gateway_getmessage($v['message_id']);

                    if (!empty($new_mgs)) {
                        // 需要根据不同的设备类型判断错误异常情况
                        $v['return_con'] = '查询消息异常';
                    } else {
                        $v['return_con'] = '查询消息异常';
                    }
                }

            } else {
                $v['return_con'] = '下发消息失败';
            }

            $orderList[$k]['customer'] = customer::getInfoByOpenid($v->openid);
            $attributes_name = isset($v['attribute_name'])?$v['attribute_name']:'  ';
            if( isset($v['goods_id']) && $v['goods_id'] == 0 && ( $v['types'] == 1 || $v['types'] == 3 ) )
            {
                if($v['types'] == 3)
                {
                    if( isset($v['number']) && $v['number'] > 0  )
                    {
                        $attributes_name = $attributes_name;
                    }
                }else
                {
                    if($v['number'] > 0)
                    {
                        $attributes_name = $attributes_name.' ';
                        if($v['is_required']==1)
                        {
                            $attributes_name .= $v['number'] .'个币';
                        }
                    }
                }
                $worketd = isset($v['worketd']) && $v['worketd'] > 0 ? ( $v['worketd'] < 60 ? $v['worketd'].'秒' :( ( $v['worketd']%60 > 0 ) ? floor( $v['worketd']/60 ).'分'.$v['worketd']%60 .'秒' : floor( $v['worketd']/60 ).'分钟' ) ) :'';
                $attributes_name = $attributes_name.'&ensp;'.$worketd;
            }
            if(($v['types'] == 2 && $v['subtype'] == 3))
            {
                $attributes_name = $attributes_name.' '.$v['number'] .'号口';
            }
            $orderList[$k]['runtime'] = $attributes_name;
        }
        $data['order'] = $orderList;
        $data['type'] = $type;
        $data['clientid'] = $clientId;
        $data['channel_id'] = $channel_id;
        return view('merchantadm.order.abnoorder',$data);
    }

    /**
     * 导出订单
     * @param Request $request
     */
    public function exportorder(Request $request)
    {
        $channel_account = $request->input('channel_account','');
        $order_number = $request->input('order_number','');
        $order_status = $request->input('order_status',0);
        $paytype = $request->input('paytype',0);
        $clientId = $request->input('clientid',0);
        $where = [];
        if(!empty(trim($channel_account)))
        {
            $where['cha.channel_account'] = $channel_account;
        }
        if(!empty(trim($order_number)))
        {
            $where['order_info.order_number'] = $order_number;
        }
        if($order_status>0)
        {
            $where['order_info.order_status'] = $order_status;
        }
        if($paytype>0)
        {
            $where['order_info.pay_id'] = $paytype;
        }
        if($clientId>0)
        {
            $where['order_info.clientid'] = $clientId;
        }
        $times = [];
        $times['k'] = !empty(trim($request->input('ktime')))?strtotime($request->input('ktime')):0;
        $times['e'] = !empty(trim($request->input('gtime')))?strtotime($request->input('gtime')):time();
        $orderList = order_info::exportorder($where,$times);
        $cellData = [
            ['订单编号','设备编号','渠道商','用户','商品','订单状态','支付金额','平台收益','下单时间']
        ];
        foreach($orderList as $k=>$v)
        {
            $aaa = $v['channel_rate'];
            $bbb = $v['pay_money'];
            $ccc = 0;
            if ($v['channel_partner_id']) {
                $channel_partner_info = channel_partner::select('rate')->where('id', $v['channel_partner_id'])->first();
                if ($channel_partner_info) {
                    $ccc = $channel_partner_info->rate;
                }
            }

            $sum_rate = sum_rate_money($bbb, $aaa, $ccc);
            $orderList[$k]['plant_money'] = $sum_rate['plant_money'];
            $customer_info = customer::getInfoByOpenid($v['openid']);
            $attributes_name = isset($v['attribute_name'])?$v['attribute_name']:'  ';
            //$orderList[$k]['runtime'] = $attributes_name;
            if ($v['order_status'] == 1 ) {
                $order_status = '未支付';
            } elseif ($v['order_status'] == 2) {
                $order_status = '已完成';
            } elseif ($v['order_status'] == 3) {
                $order_status = '已取消';
            } elseif ($v['order_status'] == 4) {
                $order_status = '退款';
            } else {
                $order_status = '未知';
            }


            $cellData[] = [
                "osv_".$v['order_number'],
                $v['clientid'],
                $v['channel_account'],
                isset($customer_info['nickname'])?$customer_info['nickname']:'',
                $attributes_name,
                $order_status,
                $v['pay_money'],
                isset($sum_rate['plant_money'])?$sum_rate['plant_money']:'',
                date('Y-m-d H:i:s', $v['add_time'])
            ];
        }
        Excel::create(date('YmdHis').'订单数据',function($excel) use ($cellData){
            $excel->sheet('score', function($sheet) use ($cellData){
                $sheet->rows($cellData);
            });
        })->export('xls');

        var_dump($orderList);die;
    }



    /**
     * 订单流水
     */
    public function capitalFlow(Request $request)
    {
        $ktime = !empty($request->input('ktime')) ? ($request->input('ktime')) : 0;
        $gtime = !empty($request->input('gtime')) ? ($request->input('gtime')) : 0;
        $channel_account = $request->input('channel_account','');
        $pay_id = $request->input('pay_id','');
        $status = $request->input('status','');
        $user_type = $request->input('user_type','');
        if($ktime==$gtime &&  $ktime){
            $ktime = date("Y-m-d H:i:s",strtotime($ktime));
            $gtime = date("Y-m-d H:i:s",(strtotime($ktime)+86400));
        }
        $where = [];
        if($channel_account) $where['channel_account'] = $channel_account;
        if($pay_id) $where['pay_type'] = $pay_id;
        if($status) $where['status'] = $status;
        if($user_type>0) $where['user_type'] = $user_type;
        $res = money_record::getList($where,$ktime,$gtime);
        //var_dump($res);exit;
        if($res){
            foreach ($res as &$v){
                if($v->user_type==0){
                    $v->account_name = "OSV";
                }elseif ($v->user_type==1){
                    //根据订单查询用户的openid再查询
                    $info = order_info::getInfoByOrderNum($v->order_number);
                    if($info){
                        $customer = customer::getInfoByOpenid($info->openid);
                        if($customer) $v->account_name = $customer['nickname'];
                    }
                }
            }
        }
        return view('merchantadm.order.capitalflow',[
            'list'=>$res,
            'channel_account'=>$channel_account,
            'pay_id'=>$pay_id,
            'status'=>$status,
            'user_type'=>$user_type,
            'ktime'=>$ktime,
            'gtime'=>$gtime,
        ]);
    }




    /**
     * [refunds 渠道商主动退款]
     * @param Request $request
     * @return
     */
    public function refunds(Request $request){
        respon(0,'该功能暂未开放');
        try{
            $data = $request->all();
            $order_num = isset($data['order_num'])?$data['order_num'] : '';
            $remarks = isset($data['remarks'])?$data['remarks'] : '';
            //$contact = isset($data['contact'])?$data['contact'] : '';
            $pwd = isset($data['password'])?$data['password'] : '';
            if(!check_pwd($pwd)) $this->respon(0, '密码错误');
            if(!$order_num){
                respon(0,'参数不能为空');
            }
            if(!$remarks){
                respon(0,'备注不能为空');
            }
            $order_info = order_info::getInfoByOrderNum($order_num);
            if(!$order_info){
                respon(0,'订单不存在');
            }
            if($order_info['dev_channel_id']==39){
                respon(0,'该类型不可退');
            }
            if($order_info['order_status'] != 2){
                respon(0,'订单类型错误');
            }
           
            $where = array(
                'id'=>$order_info['dev_channel_id'],
            );
            $channel_info = dev_channel::where($where)->first();

            if($channel_info['balance']<$order_info['pay_money']){
                respon(0,'渠道商账户余额不足');
            }
            DB::beginTransaction();
            //判断是微信还是支付宝
            if($order_info['pay_id']==1){
                $wx = new WxTransfer();
                $refund = [];
                $refund['orderNumber']=$order_info['order_number'];
                $refund['total_fee']=$order_info['pay_money'];
                if(isset($order_info['sub_mch_id']) && trim($order_info['sub_mch_id'])){
                    $refund['sub_mch_id'] = trim($order_info['sub_mch_id']);
                    $res = $wx->refund($refund,1);
                }else{
                    $res = $wx->refund($refund);
                }
            }else{
                $ali = new Alijssdk();
                $res = $ali->refund(['orderNumber'=>$order_info['order_number'],'total_fee'=>$order_info['pay_money']]);
            }
            if($res){
                if($remarks){
                    $des['remarks'] = $remarks;
                    //$des['contact'] = $contact;
                    $des = json_encode($des);
                    $res = order_sku::where(['order_id'=>$order_info['order_id']])->update(['description'=>$des]);
                    if(!$res){
                        throw new \Exception('退款失败!!');
                    }
                }
                //修改订单状态
                $result = order_info::editByOrderNumber($order_info['order_number'],['order_status'=>4, 'is_return'=>1]);
                if(!$result){
                    throw new \Exception('退款失败!');
                }
                //添加操作记录
                $res = channel_operating::addRecord($order_num,1);
                if(!$res){
                    throw new \Exception('退款失败');
                }
                //先写一条整体的收入记录
                $money_account = money_account::find(1);
                if(!$money_account){
                    $money_account = new money_account;
                    $money_account::create(['money'=>$order_info['pay_money']]);
                    $before_money = 0;
                    $after_money = $order_info['pay_money'];
                }else{
                    $money = $money_account->money;
                    if($money<=0){
                        respon(0,'账号金额错误！');
                    }
                    $before_money = $money;
                    $after_money = $money-$order_info['pay_money'];
                    $money_account->money = $after_money;
                    $money_account->save();
                }
                //添加记录
                $capital = array(
                    'user_id'=>0,
                    'user_type'=>4,
                    'type'=>2,//订单(退款)
                    'pay_type'=>$order_info['pay_id'],
                    'before_money'=>$before_money,//变更之前金额(账户余额)
                    'change_money'=>$order_info['pay_money'],//此次变更金额
                    'after_money'=>$after_money,//变更后金额
                    'status'=>3,//用户消费(收入)
                    'order_number'=>$order_info['order_number'],
                    'created_at'=>date('Y-m-d H:i:s',time()),
                );
                money_record::insertGetId($capital);
                /////todooo  ???????  平台未扣除余额
                //如果订单还没跑到渠道商的余额  直接总的减去 跟平台没关系
                if($order_info['is_settle']==0){
                    DB::commit();
                    respon(1,'退款成功!');
                }
                //计算三方的收益
                $total = sum_rate_money($order_info['pay_money'],$order_info['channel_rate'],$order_info['rate']);

                //平台抽成收益
                $plant_money = $total['plant_money'];
                if( $plant_money > 0)
                {
                    $operate = operates::where(['email' => 'yshow@e7124.com'])->first();
                    if($operate)
                    {
                        $operate = $operate->toArray();
                        $before_money = isset($operate['money'])?$operate['money']:0;
                        $after_money = $before_money - $plant_money;
                        operates::where('id',$operate['id'])->update(['money'=>$after_money]);
                        $capital = array(
                            'user_id'=>0,
                            'user_type'=>3,
                            'type'=>2,
                            'pay_type'=>$order_info['pay_id'],
                            'before_money'=>$before_money,
                            'change_money'=>$plant_money,
                            'after_money'=>$after_money,//变更后金额
                            'status'=>3,//用户消费(平台收入)
                            'order_number'=>$order_info['order_number']
                        );
                        money_record::insertGetId($capital);
                    }
                }

                $partner_money = $total['partner_money'];

                //判断 是否有 渠道商分成
                if(  ( $partner_money > 0 ) && isset( $order_info['partner_id'] ) &&  ( $order_info['partner_id'] > 0 )  )
                {
                    //合作伙伴的信息
                    $channel = dev_channel::getChannelInfo( ['id'=>$order_info['partner_id'] ] );
                    if( !empty($channel) )//合作伙伴存在并且分成比例大于0
                    {
                        $balance1 = $channel['balance'];
                        $data = array(
                            'balance'=>$balance1-$partner_money
                        );
                        dev_channel::updata( ['id'=>$order_info['partner_id'] ] , $data );
                        /*合作伙伴渠道账户添加资金流水*/
                        $capital = array(
                            'user_id'=>$channel['id'],
                            'user_type'=>2,
                            'type'=>2,
                            'pay_type'=>$order_info['pay_id'],
                            'before_money'=>$balance1 > 0 ? $balance1 : 0,//变更之前金额(账户余额)
                            'change_money'=>$partner_money,//此次变更金额
                            'after_money'=>$data['balance'],//变更后金额
                            'status'=>3,//用户消费(平台收入)
                            'order_number'=>$order_info['order_number'],
                            'created_at'=>date('Y-m-d H:i:s',time()),
                        );
                        money_record::insertGetId($capital);

                    }
                }

                //设备持有者资金变动
                $profits = $channel_info['balance'] - $total['channel_money'] ;
                $res = dev_channel::updata( $where,['balance'=>$profits] );
                if( !$res )
                {
                    $content = '修改渠道商余额错误'.$where['id'];
                    throw new \Exception($content);
                }
                /*渠道账户添加资金流水*/
                $capital = array(
                    'user_id'=>$channel_info['id'],
                    'user_type'=>2,
                    'type'=>2,
                    'pay_type'=>$order_info['pay_id'],
                    'before_money'=>$channel_info['balance'] > 0 ? $channel_info['balance'] : 0,//变更之前金额(账户余额)
                    'change_money'=>$total['channel_money'],//此次变更金额
                    'after_money'=>$profits,//变更后金额
                    'status'=>3,//用户消费(平台收入)
                    'order_number'=>$order_info['order_number'],
                    'created_at'=>date('Y-m-d H:i:s',time()),
                );
                money_record::insertGetId($capital);
                DB::commit();
                respon(1,'退款成功');
            }else{
                respon(1,'微信退款失败');
            }
        }catch (\Exception $ex){
            DB::rollback();
            respon(0, $ex->getMessage());
        }
    }
}
